package com.csun.cmny.provider.device.csun.camera;

import com.csun.cmny.provider.device.csun.camera.entity.CsunCameraConstant;
import com.csun.cmny.provider.device.watch.entity.WatchConstant;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-01-11 10:33
 * @Description:
 */
@Data
@Slf4j
public class CameraCmdProcess extends Thread {

    /**
     * netty channel
     */
    private Channel channel;

    /**
     * 待处理消息
     */
    private String message;

    /**
     * 手环imei
     */
    private String deviceNo;

    /**
     * 是否在运行 true - 正在运行
     */
    private boolean running = true;

    /**
     * 任务Id
     */
    private String taskId;

    /**
     * 命令码
     */
    private String code;

    /**
     * 重发次数
     */
    private int times = 0;

    public CameraCmdProcess(String deviceNo, String message, String taskId, String code) {
        this.channel = CsunCameraConstant.CAMERA_CHANNEL_MAP.get(deviceNo);
        this.deviceNo = deviceNo;
        this.message = message;
        this.taskId = taskId;
        this.code = code;
    }

    @Override
    public void run() {
        while (running && times < CsunCameraConstant.CAMERA_INTERVAL_FREQUENCY) {
            log.info("=====>   chisj camera process = {}, times = {}", running, times);
            if (channel != null && channel.isActive()) {
                log.info("=====>   csun camera send message: {}", message);
                channel.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
            } else {
                log.warn("=====>   csun camera channel is null or inActive.");
                running = false;
            }

            try {
                sleep(CsunCameraConstant.CAMERA_INTERVAL_TIME);
            } catch (Exception e) {
                log.error("=====>   csun camera cmd process run error: {}", e.getMessage());
            }
            times++;
        }
    }

}
